import 'dart:async';
import 'dart:convert';

import 'package:ac/data/ac_app_preferences.dart';
import 'package:ac/model/ac_blogger_model.dart';
import 'package:ac/model/ac_login_model.dart';
import 'package:ac/model/ac_video_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

import '../api/ac_urls.dart';

class AcUserManager {
  static AcLoginModel? _userInfoModel;
  static List<AcBloggerModel> bloggerList = [];
  static List<AcVideoModel> videoList = [];

  static AcLoginModel? get userInfoModel => _userInfoModel;

  static Completer initBloggerListCompleter = Completer();
  static Completer initVideoListCompleter = Completer();

  static Future<void> init() async {
    _userInfoModel = AcAppPreferences.instance.getLoginUserModel();
    if (_userInfoModel != null) {
      await updateUserInfoFromRemote();
      await _initBloggerList();
      await _initVideoList();
    }
  }

  static Future<void> updateUserInfoFromRemote() async {
    var result = await AcUrls.getUserInfo.get(
      queryParameters: {"userId": _userInfoModel!.userInfo.userId},
      showLoading: false,
      showErrorMessage: false,
    );
    if (result?["code"] == 0) {
      var data = result['data'];
      var userinfo = Userinfo.fromJson(data);
      updateLoginUserInfo(userinfo);
    }
  }

  static Future<void> logout() async {
    AcAppPreferences.instance
        .setBloggerList(null, _userInfoModel!.userInfo.userId!);
    _userInfoModel = null;
    bloggerList.clear();
    videoList.clear();
    AcAppPreferences.instance.setUserModel(null);
  }

  static Future<void> setUserInfoModel(AcLoginModel? userInfoModel) async {
    _userInfoModel = userInfoModel;
    AcAppPreferences.instance.setUserModel(userInfoModel);
    initVideoListCompleter = Completer();
    initBloggerListCompleter = Completer();
    if (userInfoModel != null) {
      await _initBloggerList();
      await _initVideoList();
    }
  }

  static Future<void> updateBloggers() async {
    if (_userInfoModel == null) {
      return;
    }
    AcAppPreferences.instance
        .setBloggerList(bloggerList, userInfoModel!.userInfo.userId!);
  }

  static Future<void> updateVideos() async {
    if (_userInfoModel == null) {
      return;
    }
    AcAppPreferences.instance
        .setVideoList(videoList, userInfoModel!.userInfo.userId!);
  }

  static Future<void> updatePostData(Post post) async {
    for (var value in bloggerList) {
      if (value.post.contains(post)) {
        value.post.remove(post);
        value.post.add(post);
        break;
      }
    }
    updateBloggers();
  }

  static Future<void> updateBloggerUserInfo(Userinfo userinfo) async {
    for (var value in bloggerList) {
      if (value.userInfo?.userId == userinfo.userId) {
        value.userInfo = userinfo;
        break;
      }
    }
    updateBloggers();
  }

  static Future<void> updateVideoUserInfo(Userinfo userinfo) async {
    for (var value in videoList) {
      if (value.userInfo?.userId == userinfo.userId) {
        value.userInfo = userinfo;
        break;
      }
    }
    updateVideos();
  }

  static Userinfo? getUserInfo(String userId) {
    for (var value in bloggerList) {
      if (value.userInfo?.userId == userId) {
        return value.userInfo;
      }
    }
    return null;
  }

  // Method to get user token
  static String? getFoToken() {
    if (_userInfoModel == null) {
      return null;
    }
    return _userInfoModel!.token;
  }

  static Future<void> _initBloggerList() async {
    var localList = AcAppPreferences.instance
        .getBloggerList(userInfoModel!.userInfo.userId!);
    if (localList.isNotEmpty) {
      bloggerList = localList;
      initBloggerListCompleter.complete();
      return;
    }

    var postStr = await rootBundle.loadString("images/post/post.json");
    List list = jsonDecode(postStr);
    bloggerList.clear();
    for (var item in list) {
      bloggerList.add(AcBloggerModel.fromJson(item));
    }
    AcAppPreferences.instance
        .setBloggerList(bloggerList, userInfoModel!.userInfo.userId!);
    await _getBloggerInfoList((list) {
      if (list.isEmpty) {
        initBloggerListCompleter.completeError(list);
      }
      for (var i = 0; i < bloggerList.length; ++i) {
        var item = list[i];
        Userinfo userinfo = Userinfo.fromJson(item);
        bloggerList[i].userInfo = userinfo;
      }
      updateBloggers();
      initBloggerListCompleter.complete();
    });
  }

  static Future<void> _initVideoList() async {
    var localList =
        AcAppPreferences.instance.getVideoList(userInfoModel!.userInfo.userId!);
    if (localList.isNotEmpty) {
      videoList = localList;
      initVideoListCompleter.complete();
      return;
    }

    var videoStr = await rootBundle.loadString("images/post/video.json");
    List list = jsonDecode(videoStr);
    videoList.clear();
    for (var item in list) {
      videoList.add(AcVideoModel.fromJson(item));
    }
    AcAppPreferences.instance
        .setVideoList(videoList, userInfoModel!.userInfo.userId!);
    await _getBloggerInfoList((list) {
      if (list.isEmpty) {
        initVideoListCompleter.completeError(list);
      }
      for (var i = 0; i < videoList.length; ++i) {
        var item = list[i];
        Userinfo userinfo = Userinfo.fromJson(item);
        videoList[i].userInfo = userinfo;
      }
      initVideoListCompleter.complete();
      updateVideos();
    });
  }

  static List userList = [];

  static Future<void> _getBloggerInfoList(ValueSetter<List> callBack) async {
    if (userList.isNotEmpty) {
      callBack(userList);
      return;
    }
    var result = await AcUrls.getUserInfoList
        .post(showLoading: false, showErrorMessage: false, data: {
      "category": "Popular", // 分类固定传Popular
      "isPageMode": true,
      "isRemoteImageUrl": true, // 必须为true 否则返回的头像链接需要拼接
      "limit": 20,
      "page": 1,
      "tag": "All",
    });
    if (result?["code"] == 0) {
      var list = result['data'];
      userList = list;
      callBack(list);
    } else {
      callBack([]);
    }
  }

  static void publishPost(Post post) {
    var str = jsonEncode(post.toJson());
    AcAppPreferences.instance
        .addPublishPost(str, userInfoModel!.userInfo.userId!);
  }

  // 获取发布的贴
  static List<Post> getPublishPost() {
    var list = AcAppPreferences.instance
        .getPublishPost(userInfoModel!.userInfo.userId!);
    return list;
  }

  // 更新发布的贴
  static void updatePublishPost(String oldJson, String newJson) {
    AcAppPreferences.instance
        .updatePublishPost(oldJson, newJson, userInfoModel!.userInfo.userId!);
  }

  static void deletePost(Post item) {
    AcAppPreferences.instance.removePublishPost(
        userInfoModel!.userInfo.userId!, jsonEncode(item.toJson()));
  }

  static void updateLoginUserInfo(Userinfo userinfo) {
    _userInfoModel!.userInfo = userinfo;
    AcAppPreferences.instance.setUserModel(_userInfoModel);
  }
}

// Example model class for user information
class UserInfoModel {
  String foToken;

  UserInfoModel(this.foToken);
}
